package com.fdb.efp.batch.service.impl.bd;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.fdb.basic.framework.core.constant.MonAlrmLvlEnums.MonAlrmLvlEnum;
import com.fdb.basic.framework.core.util.DateTool;
import com.fdb.basic.framework.core.util.DateUtility;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.basic.framework.core.util.TimeUtil;
import com.fdb.efp.batch.common.constant.BdLoanConstant;
import com.fdb.efp.batch.service.facade.bd.BdLoanRepayPlanBatchService;
import com.fdb.efp.batch.service.util.DueDataUtil;
import com.fdb.efp.loan.common.LoanConstant;
import com.fdb.efp.loan.service.facade.AccLoanService;
import com.fdb.efp.loan.service.facade.AccoutErroTempService;
import com.fdb.efp.loan.service.facade.BdRepayPlanTempService;
import com.fdb.efp.loan.service.facade.LoanRepayPlanService;
import com.fdb.efp.loan.service.vo.AccLoanVO;
import com.fdb.efp.loan.service.vo.AccoutErroTempVO;
import com.fdb.efp.loan.service.vo.BdRepayPlanTempVO;
import com.fdb.efp.loan.service.vo.LoanRepayPlanVO;
import com.fdb.efp.nls.service.facade.BdLoanpayService;
import com.fdb.efp.nls.service.facade.NlsApplyInfoService;

/**
 * @description: 根据百度同步过来的还款计划临时表信息修改还款计划表
 * 
 * @author ludayong
 * @date:2019年3月6日 下午7:54:16
 * @version 1.0
 */
@Service("bdLoanRepayPlanBatchService")
public class BdLoanRepayPlanBatchServiceImpl implements BdLoanRepayPlanBatchService {
	private static Logger logger = LoggerFactory.getLogger(BdLoanRepayPlanBatchServiceImpl.class);

	@Autowired
	@Qualifier("accLoanRepayPlanService")
	private LoanRepayPlanService loanRepayPlanService;// 还款计划信息

	@Autowired
	@Qualifier("bdRepayPlanTempService")
	private BdRepayPlanTempService bdRepayPlanTempService;// 百度还款计划临时数据信息

	@Autowired
	@Qualifier("accoutErroTempService")
	private AccoutErroTempService accoutErroTempService;// 错误信息

	@Autowired
	@Qualifier("accLoanService")
	private AccLoanService accLoanService;// 借据信息

	// @Autowired
	// @Qualifier("bdDnDetailTempService")
	// private BdDnDetailTempService bdDnDetailTempService;// 放款明细临时信息
	@Autowired
	@Qualifier("bdLoanpayService")
	private BdLoanpayService bdLoanpayService;// 百度放款通知记录信息

	@Autowired
	@Qualifier("nlsApplyInfoService")
	private NlsApplyInfoService nlsApplyInfoService;// 网贷申请信息

	/**
	 * 
	 * 根据百度同步过来的还款计划临时表信息修改还款计划表<br>
	 * 
	 * @author ludayong
	 * @since 2019年3月7日 上午8:52:02
	 * @date 2019年3月7日 上午8:52:02
	 * @version 0.1
	 */
	public boolean batchUpdateLoanRepayPlan() throws Exception {
		boolean result = false;
		long startTime = System.currentTimeMillis();
		logger.info("同步百度还款计划临时数据到还款计划表：[" + DateTool.formatDate(new Date(startTime), DateTool.PATTERN_DATETIME) + "]， 处理开始");
		// 可以配置参数
		Integer pageSize = 100;
		// 需要新增或者修改的还款计划表
		List<LoanRepayPlanVO> list = null;
		try {
			// 分页信息
			BdRepayPlanTempVO pageInfo = new BdRepayPlanTempVO();
			// 新增或者修改的还款计划数量
			int num = 0;
			// 页数
			int page = 1;
			// pageSize初始化
			if (pageSize > 0) {
				pageInfo.setSize(pageSize);
			} else {
				pageInfo.setSize(1000);
			}
			// 新增或者修改
			// int insertOrUpdateNum = 0;
			// 判断循环次数
			int size = bdRepayPlanTempService.queryCount();
			String size_msg = "【还款计划明细临时表】借据数据量：" + size;
			logger.info(size_msg, "message{}");
			int loopCount = (size / pageInfo.getSize()) + 1;

			// 放款信息
			// BdDnDetailTempVO inBdDnDetailTempVO = new BdDnDetailTempVO();
			// 百度放款通知记录信息
			// BdLoanpayVO inBdLoanpayVO = new BdLoanpayVO();
			// 网贷申请基本信息
			// NlsApplyInfoVO inNlsApplyInfoVO = new NlsApplyInfoVO();
			// 借据信息
			AccLoanVO inAccLoanVO = new AccLoanVO();
			// 借据号
			// String bdLoanId = null;
			for (int i = 0; i < loopCount; i++) {
				String page_msg = "【还款计划明细临时表】当前页数：" + pageInfo.getPage() + "，分页大小：" + pageInfo.getSize();
				logger.info(page_msg, "message{}");
				// 分页查询【还款计划明细表】数据
				List<BdRepayPlanTempVO> tempList = bdRepayPlanTempService.queryByPage(pageInfo);
				if (Objects.nonNull(tempList) && !tempList.isEmpty()) {
					// 需要新增或者修改的还款计划表
					list = new ArrayList<LoanRepayPlanVO>();
					for (BdRepayPlanTempVO bdRepayPlanTempVO : tempList) {
						// 新增或者修改数量
						// insertOrUpdateNum = 0;
						// bdLoanId = bdRepayPlanTempVO.getLoanId();
						// 放款明细入参
						// inBdDnDetailTempVO.setLoanId(bdLoanId);
						// 查询的放款信息
						// BdDnDetailTempVO queryBdDnDetailTempVO =
						// bdDnDetailTempService.queryByPk(inBdDnDetailTempVO);
						// 百度放款通知记录信息
						// inBdLoanpayVO.setLoanId(bdLoanId);
						// 查询百度放款通知记录信息
						// BdLoanpayVO queryBdLoanpayVO = bdLoanpayService.queryByPk(inBdLoanpayVO);
						// String orderId = "";
						// if (Objects.nonNull(queryBdLoanpayVO)) {
						// // 订单号
						// orderId = queryBdLoanpayVO.getOrderId();
						// } else {
						// String tableName = "bd_loanpay";
						// String errorMsg = "未查询到还款计划信息关联的百度放款通知记录信息，借据号：" + bdLoanId;
						// addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg,
						// errorMsg);
						// logger.error(errorMsg);
						// }
						// 网贷用信申请流水号
						// String applySeq = "";
						// 订单号非空
						// if (!StringUtil.isNullorBank(orderId)) {
						// // 订单号
						// inNlsApplyInfoVO.setBdOrderId(orderId);
						// // 查询的网贷申请基本信息
						// NlsApplyInfoVO queryNlsApplyInfoVO =
						// nlsApplyInfoService.queryByPk(inNlsApplyInfoVO);
						// if (Objects.nonNull(queryNlsApplyInfoVO)) {
						// // 网贷用信申请流水号s
						// applySeq = queryNlsApplyInfoVO.getApplySeq();
						// } else {
						// String tableName = "nls_apply_info";
						// String errorMsg = "未查询到还款计划信息关联的网贷申请基本信息，放款订单号：" + orderId + "，借据号：" +
						// bdLoanId;
						// addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg,
						// errorMsg);
						// logger.error(errorMsg);
						// }
						// }
						// 网贷用信申请流水号非空
						// if (!StringUtil.isNullorBank(applySeq)) {
						// 设置借据号
						inAccLoanVO.setBillNo(bdRepayPlanTempVO.getLoanId());
						AccLoanVO queryAccLoanVo = accLoanService.queryByPk(inAccLoanVO);
						// 1.1根据还款信息借据临时信息的借据号查询借据信息是否存在，存在：进行下一步操作，不存在：记录异常信息
						boolean accLoanIsExit = false;
						if (Objects.nonNull(queryAccLoanVo)) {
							accLoanIsExit = true;
						} else {
							String tableName = "acc_loan";
							String errorMsg = "未查询到还款计划临时信息关联的借据信息";
							addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg, errorMsg);
							logger.error(errorMsg);
						}
						if (accLoanIsExit) {
							// 根据借据号查询还款计划临时信息
							BdRepayPlanTempVO bdRepayPlanTemp = new BdRepayPlanTempVO();
							bdRepayPlanTemp.setLoanId(bdRepayPlanTempVO.getLoanId());
							// 根据借据号查询还款计划临时信息
							List<BdRepayPlanTempVO> tempListAll = bdRepayPlanTempService.queryBdRepayPlanTempByLoanId(bdRepayPlanTemp);
							// 根据借据号查询还款计划信息
							LoanRepayPlanVO inLoanRepayPlanVo = new LoanRepayPlanVO();
							inLoanRepayPlanVo.setRefNbr(bdRepayPlanTempVO.getLoanId());
							// 根据借据号查询还款计划信息
							List<LoanRepayPlanVO> listAll = loanRepayPlanService.queryAllLoanRepayPlan(inLoanRepayPlanVo);
							// 还款计划信息转Map
							Map<String, LoanRepayPlanVO> repayPlanMap = new HashMap<String, LoanRepayPlanVO>();
							if (Objects.nonNull(listAll) && !listAll.isEmpty()) {
								for (LoanRepayPlanVO loanRepayPlanVO : listAll) {
									if (Objects.nonNull(loanRepayPlanVO)) {
										repayPlanMap.put(loanRepayPlanVO.getRefNbr() + loanRepayPlanVO.getTerm(), loanRepayPlanVO);
									}
								}
							}
							if (Objects.nonNull(tempListAll) && !tempListAll.isEmpty()) {
								for (BdRepayPlanTempVO bdRepayPlanTem : tempListAll) {
									// 需要新增或更新还款信息借据正式表LoanRepayDetail
									LoanRepayPlanVO loanRepayPlanInfo = initLoanRepayPlan(bdRepayPlanTem, queryAccLoanVo, repayPlanMap);
									if (Objects.nonNull(loanRepayPlanInfo)) {
										list.add(loanRepayPlanInfo);
									}
								}
								// 如果还款计划当期更新为提前结清，后续还款计划删除
								// checkLoanRepayPlanSettlment(tempListAll, queryAccLoanVo);
								// 最高逾期期数
								int maxTimesTotal = this.getLoanRepayMaxTimesTotal(tempListAll);
								BigDecimal maxTotal = queryAccLoanVo.getMaxTimesTotal() == null ? BigDecimal.ZERO
										: queryAccLoanVo.getMaxTimesTotal();
								if (new BigDecimal(maxTimesTotal).compareTo(maxTotal) > 0) {
									queryAccLoanVo.setMaxTimesTotal(new BigDecimal(maxTimesTotal));
									logger.info("最高逾期期数为：" + maxTimesTotal);
								}
								// 逾期起时日
								String capOverdueDate = getLoanCapOverdueDate(tempListAll);
								queryAccLoanVo.setCapOverdueDate(capOverdueDate);
								int loanNum = accLoanService.updateByPk(queryAccLoanVo);
								if (loanNum != 1) {
									String tableName = "acc_loan";
									String errorMsg = "同步百度还款计划临时信息更新还款计划信息表出错，借据号:" + bdRepayPlanTempVO.getLoanId();
									addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg, errorMsg);
									logger.error(errorMsg);
								}
							}
						}
						// }
					}
					if (list != null && !list.isEmpty()) {
						int addNum = loanRepayPlanService.insertOrUpdateLoanRepayPlan(list);
						if (addNum == -1) {
							String tableName = "loan_repay_plan";
							String errorMsg = "同步百度还款计划临时信息更新还款计划信息表出错，当前页数：" + pageInfo.getPage() + "，分页大小：" + pageInfo.getSize();
							addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg, errorMsg);
							logger.error(errorMsg);
						} else {
							num += addNum;
						}
					}
				}
				pageInfo.setPage(++page);
			}
			String num_msg = "【百度还款计划表】插入或更新数据处理结果:" + num;
			logger.info(num_msg, "message{}");
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			String tableName = "loan_repay_plan";
			String errorMsg = "同步百度还款计划临时信息更新还款计划信息表出错";
			String remark = "同步百度还款计划临时信息更新还款计划信息表出错，错误信息：" + e.getMessage();
			addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg, remark);
			logger.error(remark);
			throw new Exception(remark);
		} finally {
			list = null;
		}
		long endTime = System.currentTimeMillis();
		logger.info("同步百度还款计划临时数据到还款计划表：[" + DateTool.formatDate(new Date(endTime), DateTool.PATTERN_DATETIME) + "]， 处理结束");
		logger.info("同步百度还款计划临时数据到还款计划表，耗时：[" + (endTime - startTime) / 1000.0 + "]秒，处理结果[" + result + "]");
		return result;
	}

	/**
	 * 
	 * 根据还款计划临时信息的借据号查询还款计划正式表信息是否存在 <br>
	 * 0.1:ludayong:2019年3月8日 上午9:03:27:新增 <br>
	 * 
	 * @author ludayong
	 * @since 2019年3月8日 上午9:03:27
	 * @date 2019年3月8日 上午9:03:27
	 * @version 0.1
	 */
	public boolean queryLoanRepayPlanInfo(BdRepayPlanTempVO bdRepayPlanTem) {
		boolean isExit = false;
		LoanRepayPlanVO loanRepayPlanBy = new LoanRepayPlanVO();
		if (Objects.nonNull(bdRepayPlanTem)) {
			// 借据编号
			loanRepayPlanBy.setRefNbr(bdRepayPlanTem.getLoanId());
			loanRepayPlanBy.setTerm(bdRepayPlanTem.getTermNo().intValue());
			// 查询还款计划正式表信息是否存在
			LoanRepayPlanVO queryLoanRepayPlanVO = loanRepayPlanService.getLoanRepayPlanByRefNbrAndTerm(loanRepayPlanBy);
			if (Objects.nonNull(queryLoanRepayPlanVO)) {
				isExit = true;
			}
		}
		return isExit;
	}

	/**
	 * 
	 * 根据还款信息借据临时信息初始化还款计划信息 <br>
	 * 0.1:ludayong:2019年3月11日 下午9:10:21:新增 <br>
	 * 
	 * @author ludayong
	 * @since 2019年3月11日 下午9:10:21
	 * @date 2019年3月11日 下午9:10:21
	 * @version 0.1
	 */
	public LoanRepayPlanVO initLoanRepayPlan(BdRepayPlanTempVO bdRepayPlanTempVo, AccLoanVO accLoanVo,
			Map<String, LoanRepayPlanVO> repayPlanMap) {
		LoanRepayPlanVO queryLoanRepayPlanVO = null;
		if (Objects.nonNull(bdRepayPlanTempVo)) {
			// 查询还款计划正式表信息是否存在
			queryLoanRepayPlanVO = repayPlanMap.get(bdRepayPlanTempVo.getLoanId() + bdRepayPlanTempVo.getTermNo());
		}
		LoanRepayPlanVO newLoanRepayPlanVo = null;
		if (Objects.nonNull(queryLoanRepayPlanVO)) {
			if ("P".equals(queryLoanRepayPlanVO.getStatus())) {
				return newLoanRepayPlanVo;
			}
			// 初始化信息
			queryLoanRepayPlanVO = initLoanRepayPlanInfo(bdRepayPlanTempVo, queryLoanRepayPlanVO, accLoanVo);
			return queryLoanRepayPlanVO;
		} else {
			// 还款信息借据正式表LoanRepayPlan信息
			newLoanRepayPlanVo = new LoanRepayPlanVO();
			// loan_id 借据号 contr_nbr 合同号
			// newLoanRepayPlanVo.setContrNbr(contNo);
			// ref_nbr 借据号 contr_nbr 贷款编号
			newLoanRepayPlanVo.setRefNbr(accLoanVo.getBillNo());
			// principal_due_91 非应计本金
			newLoanRepayPlanVo.setPrincipalDue91(BigDecimal.ZERO);
			// principal_due 逾期本金
			newLoanRepayPlanVo.setPrincipalDue(BigDecimal.ZERO);
			// interest_due 逾期利息
			newLoanRepayPlanVo.setInterestDue(BigDecimal.ZERO);
			// interest_due_91 表外利息
			newLoanRepayPlanVo.setInterestDue91(BigDecimal.ZERO);
			// init_term 还款总期数
			newLoanRepayPlanVo.setInitTerm(0);
			// 初始化信息
			newLoanRepayPlanVo = initLoanRepayPlanInfo(bdRepayPlanTempVo, newLoanRepayPlanVo, accLoanVo);
			return newLoanRepayPlanVo;
		}
	}

	/**
	 * 
	 * 根据还款信息借据临时信息初始化还款计划信息 <br>
	 * 0.1:ludayong:2019年3月11日 下午9:10:21:新增 <br>
	 * 
	 * @author ludayong
	 * @since 2019年3月11日 下午9:10:21
	 * @date 2019年3月11日 下午9:10:21
	 * @version 0.1
	 */
	public LoanRepayPlanVO initLoanRepayPlanInfo(BdRepayPlanTempVO bdRepayPlanTempVo, LoanRepayPlanVO loanRepayPlanVo,
			AccLoanVO accLoanVo) {
		// 逾期
		if (BdLoanConstant.TERM_STATUS_2.equals(bdRepayPlanTempVo.getTermStatus())) {
			// 违约标志
			loanRepayPlanVo.setOverdueFlag("1");
		} else {
			if (!BdLoanConstant.YES_1.equals(loanRepayPlanVo.getOverdueFlag())) {
				loanRepayPlanVo.setOverdueFlag("0");
			}
		}
		// 贷款期限
		BigDecimal loanTerm = accLoanVo.getLoanTerm();
		if (Objects.nonNull(loanTerm)) {
			loanRepayPlanVo.setInitTerm(loanTerm.intValue());
		}
		// 产品编号
		loanRepayPlanVo.setProductCd(accLoanVo.getPrdCode());
		// 合同号
		loanRepayPlanVo.setContrNbr(accLoanVo.getApplySeq());
		// prin_total 应还本金 principal 本金
		loanRepayPlanVo.setPrincipal(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getPrinTotal(), 100));
		// prin_repay 已还本金 principal_paid 已还本金
		loanRepayPlanVo.setPrincipalPaid(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getPrinRepay(), 100));
		// int_total 应还利息 interest 利息
		loanRepayPlanVo.setInterest(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getIntTotal(), 100));
		// int_repay 已还利息 interest_paid 已还利息
		loanRepayPlanVo.setInterestPaid(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getIntRepay(), 100));
		// interest_due 逾期利息
		// pnlt_int_total 应还罚息 penalty_due 罚息
		loanRepayPlanVo.setPenaltyDue(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getPnltIntTotal(), 100));
		// pnlt_int_repay 已还罚息 penalty_paid 已还罚息
		loanRepayPlanVo.setPenaltyPaid(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getPnltIntRepay(), 100));
		// term_status 本期状态 status 期数状态
		loanRepayPlanVo.setStatus(termStatusTrans(bdRepayPlanTempVo.getTermStatus()));
		// term_no 期序 term 还款期数
		loanRepayPlanVo.setTerm(bdRepayPlanTempVo.getTermNo().intValue());
		// cur_date 账务日期 biz_date 业务日期
		loanRepayPlanVo.setBizDate(DueDataUtil.dateInfoTrans(bdRepayPlanTempVo.getCurDate()));
		// start_date 开始日期 begin_date 开始日期
		loanRepayPlanVo.setBeginDate(DueDataUtil.dateInfoTrans(bdRepayPlanTempVo.getStartDate()));
		// end_date 到期日期 stmt_date 到期日期
		loanRepayPlanVo.setStmtDate(DueDataUtil.dateInfoTrans(bdRepayPlanTempVo.getEndDate()));
		// 宽限期到期日
		String graceDate = "";
		try {
			// 宽限期
			BigDecimal graceDay = accLoanVo.getGraceDay();
			if (Objects.nonNull(graceDay)) {
				graceDate = TimeUtil.addDay(DueDataUtil.dateInfoTrans(bdRepayPlanTempVo.getEndDate()), graceDay.intValue());
				loanRepayPlanVo.setGraceDate(graceDate);
			} else {
				loanRepayPlanVo.setGraceDate(graceDate);
			}
		} catch (Exception e) {
			loanRepayPlanVo.setGraceDate(graceDate);
			e.printStackTrace();
			logger.error("*****************宽限期到期日转换失败*****************");
		}
		// clear_date 结清日期
		loanRepayPlanVo.setClearDate(DueDataUtil.dateInfoTrans(bdRepayPlanTempVo.getClearDate()));
		// fund_fee_total 应还借款服务费
		loanRepayPlanVo.setFundFeeTotal(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getFundFeeTotal(), 100));
		// fund_fee_repay 已还借款服务费
		loanRepayPlanVo.setFundFeeRepay(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getFundFeeRepay(), 100));
		// int_reduced_amt_coupon 优惠券抵扣利息金额
		loanRepayPlanVo.setIntReducedAmtCoupon(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getIntReducedAmtCoupon(), 100));
		// pnlt_reduced_amt_coupon 优惠券抵扣罚息金额
		loanRepayPlanVo.setPnltReducedAmtCoupon(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getPnltReducedAmtCoupon(), 100));
		// fund_fee_reduced_amt_coupon 优惠券抵扣借款服务费金额
		loanRepayPlanVo.setFundFeeReducedAmtCoupon(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getFundFeeReducedAmtCoupon(), 100));
		// charges_total 应还分期手续费
		loanRepayPlanVo.setChargesTotal(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getChargesTotal(), 100));
		// charges_repay 已还分期手续费
		loanRepayPlanVo.setChargesRepay(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getChargesRepay(), 100));
		// overdue_total 应还逾期费
		loanRepayPlanVo.setOverdueTotal(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getOverdueTotal(), 100));
		// overdue_repay 已还逾期费
		loanRepayPlanVo.setOverdueRepay(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getOverdueRepay(), 100));
		// repay_violate_total 应还提前还款违约金
		loanRepayPlanVo.setRepayViolateTotal(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getRepayViolateTotal(), 100));
		// repay_violate_repay 已还提前还款违约金
		loanRepayPlanVo.setRepayViolateRepay(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getRepayViolateRepay(), 100));
		// refund_violate_total 应还退款违约金
		loanRepayPlanVo.setRefundViolateTotal(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getRefundViolateTotal(), 100));
		// refund_violate_repay 已还退款违约金
		loanRepayPlanVo.setRefundViolateRepay(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getRefundViolateRepay(), 100));
		// service_total 应还担保费
		loanRepayPlanVo.setServiceTotal(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getServiceTotal(), 100));
		// service_repay 已还担保费
		loanRepayPlanVo.setServiceRepay(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getServiceRepay(), 100));
		// charges_reduced_amt_coupon 优惠券抵扣分期手续费金额
		loanRepayPlanVo.setChargesReducedAmtCoupon(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getChargesReducedAmtCoupon(), 100));
		// overdue_reduced_amt_coupon 优惠券抵扣逾期费金额
		loanRepayPlanVo.setOverdueReducedAmtCoupon(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getOverdueReducedAmtCoupon(), 100));
		// repay_violate_reduced_amt_coupon 优惠券抵扣提前还款违约金金额
		loanRepayPlanVo
				.setRepayViolateReducedAmtCoupon(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getRepayViolateReducedAmtCoupon(), 100));
		// refund_violate_reduced_amt_coupon 优惠券抵扣退款违约金金额
		loanRepayPlanVo
				.setRefundViolateReducedAmtCoupon(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getRefundViolateReducedAmtCoupon(), 100));
		// service_reduced_amt_coupon 优惠券抵扣担保费金额
		loanRepayPlanVo.setServiceReducedAmtCoupon(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getServiceReducedAmtCoupon(), 100));
		// prin_reduced_amt_manual 手工减免本金金额
		loanRepayPlanVo.setPrinReducedAmtManual(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getPrinReducedAmtManual(), 100));
		// int_reduced_amt_manual 手工减免利息金额
		loanRepayPlanVo.setIntReducedAmtManual(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getIntReducedAmtManual(), 100));
		// pnlt_reduced_amt_manual 手工减免罚息金额
		loanRepayPlanVo.setPnltReducedAmtManual(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getPnltReducedAmtManual(), 100));
		// fund_fee_reduced_amt_manual 手工减免借款服务费金额
		loanRepayPlanVo.setFundFeeReducedAmtManual(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getFundFeeReducedAmtManual(), 100));
		// charges_reduced_amt_manual 手工减免分期手续费
		loanRepayPlanVo.setChargesReducedAmtManual(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getChargesReducedAmtManual(), 100));
		// overdue_reduced_amt_manual 手工减免逾期费
		loanRepayPlanVo.setOverdueReducedAmtManual(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getOverdueReducedAmtManual(), 100));
		// repay_violate_reduced_amt_manual 手工减免提前还款违约金
		loanRepayPlanVo
				.setRepayViolateReducedAmtManual(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getRepayViolateReducedAmtManual(), 100));
		// refund_violate_reduced_amt_manual 手工减免退款违约金
		loanRepayPlanVo
				.setRefundViolateReducedAmtManual(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getRefundViolateReducedAmtManual(), 100));
		// service_reduced_amt_manual 手工减免担保费
		loanRepayPlanVo.setServiceReducedAmtManual(DueDataUtil.checkDecimalInfo(bdRepayPlanTempVo.getServiceReducedAmtManual(), 100));
		return loanRepayPlanVo;
	}

	/**
	 * 
	 * 期数状态转换<br>
	 * 0.1:ludayong:2019年3月20日 下午7:05:11:新增 <br>
	 * 
	 * @author ludayong
	 * @since 2019年3月20日 下午7:05:11
	 * @date 2019年3月20日 下午7:05:11
	 * @version 0.1
	 */
	private String termStatusTrans(String termStatus) {
		if (StringUtil.isNullorBank(termStatus)) {// 期数状态为空
			return "";
		}
		// F 非应计
		// N 正常
		// O 逾期
		// P 结清
		// C 撤销
		// R 冲正

		// 1：正常
		// 2：逾期
		// 3：已冲正
		// 4：已撤销
		// 5：已结清
		// 新的期数状态
		String newTermStatus = "";
		switch (termStatus) {
		case BdLoanConstant.TERM_STATUS_1:
			newTermStatus = "N";
			break;
		case BdLoanConstant.TERM_STATUS_2:
			newTermStatus = "O";
			break;
		case BdLoanConstant.TERM_STATUS_3:
			newTermStatus = "R";
			break;
		case BdLoanConstant.TERM_STATUS_4:
			newTermStatus = "C";
			break;
		case BdLoanConstant.TERM_STATUS_5:
			newTermStatus = "P";
			break;
		default:
		}
		return newTermStatus;
	}

	/**
	 * 
	 * 获取还款计划结清期数、如果还款计划当期更新为提前结清，后续计删除 <br>
	 * 0.1:ludayong:2019年5月23日 下午7:34:36:新增 <br>
	 * 
	 * @author ludayong
	 * @since 2019年5月23日 下午7:34:36
	 * @date 2019年5月23日 下午7:34:36
	 * @version 0.1
	 */
	private void checkLoanRepayPlanSettlment(List<BdRepayPlanTempVO> bdRepayPlanTempList, AccLoanVO queryAccLoanVo) {
		// 期数
		int termNo = 0;
		// 借据号
		String loanId = "";
		// 借据号下的还款计划信息
		if (Objects.nonNull(bdRepayPlanTempList) && !bdRepayPlanTempList.isEmpty()) {
			for (BdRepayPlanTempVO bdRepayPlanTem : bdRepayPlanTempList) {
				// 借据状态为：结清
				if (LoanConstant.TZZT_JQ.equals(queryAccLoanVo.getAccountStatus())) {
					// 期数
					termNo = queryAccLoanVo.getCurrTerm() == null ? 0 : queryAccLoanVo.getCurrTerm().intValue();
					// 借据号
					loanId = bdRepayPlanTem.getLoanId();
					break;
				}
			}
		}
		if (termNo > 0 && !StringUtil.isNullorBank(loanId)) {
			// 结清期数不为最后一期
			if (Objects.nonNull(bdRepayPlanTempList) && termNo != bdRepayPlanTempList.size()) {
				LoanRepayPlanVO loanRepayPlan = new LoanRepayPlanVO();
				// 期数
				loanRepayPlan.setTerm(termNo);
				// 借据号
				loanRepayPlan.setRefNbr(loanId);
				int num = loanRepayPlanService.deleteByRefNbrAndTerm(loanRepayPlan);
				logger.info("删除本地表 条件为 当前的借据号 和 >curr_term期数还款计划数据 ，结束，返回值num：" + num);
				if (num == -1) {
					String tableName = "loan_repay_plan";
					String errorMsg = "还款计划当期为提前结清，删除提前结清期数后续的计划出错";
					String remark = "还款计划当期为提前结清，删除提前结清期数后续的计划出错，借据号：" + loanId;
					addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg, remark);
					logger.error(remark);
				}
			}
		}
	}

	/**
	 * 
	 * 记录异常信息 <br>
	 * 0.1:ludayong:2019年3月8日 上午8:40:46:新增 <br>
	 * 
	 * @author ludayong
	 * @since 2019年3月8日 上午8:40:46
	 * @date 2019年3月8日 上午8:40:46
	 * @version 0.1
	 */
	private void addErrorInfo(String tableName, String errorType, String errorMsg, String remark) {
		AccoutErroTempVO accoutErroTempVO = new AccoutErroTempVO();
		// 表名
		accoutErroTempVO.setTableName(tableName);
		// 错误级别
		accoutErroTempVO.setErroType(errorType);
		// 错误信息
		accoutErroTempVO.setErroMsg(errorMsg);
		// 备注
		accoutErroTempVO.setRemark(remark);
		// 创建时间
		accoutErroTempVO.setCreateData(DateTool.getCurrentDateTime());
		// 修改时间
		accoutErroTempVO.setLastModifyTime(DateTool.getCurrentDateTime());
		// 记录异常信息
		accoutErroTempService.insert(accoutErroTempVO);
	}

	/**
	 * 
	 * 获取最高逾期期数 <br>
	 * 0.2:ludayong:2019年3月6日 上午8:36:22:新增 <br>
	 * 
	 * @author ludayong
	 * @since 2019年7月31日 上午8:36:22
	 * @date 2019年7月31日 上午8:36:22
	 * @version 0.1 初始为0.1,后续变更则修改
	 */
	private int getLoanRepayMaxTimesTotal(List<BdRepayPlanTempVO> tempListAll) {
		int maxTimesTotal = 0;// 最大的违约次数
		int count = 0;// 记数器
		if (Objects.nonNull(tempListAll)) {
			for (int i = 0; i < tempListAll.size(); i++) {
				BdRepayPlanTempVO bdRepayPlanTempVO = tempListAll.get(i);
				if (BdLoanConstant.TERM_STATUS_2.equals(bdRepayPlanTempVO.getTermStatus())) {
					count++;
				} else {
					if (count > maxTimesTotal) {
						maxTimesTotal = count;
					}
					count = 0;// 恢复计数
				}
			}
			if (count > maxTimesTotal) {
				maxTimesTotal = count;
			}
		}
		return maxTimesTotal;
	}

	/**
	 * 
	 * 获取逾期起时日 <br>
	 * 0.2:ludayong:2019年3月6日 上午8:36:22:新增 <br>
	 * 
	 * @author ludayong
	 * @since 2019年7月31日 上午8:36:22
	 * @date 2019年7月31日 上午8:36:22
	 * @version 0.1 初始为0.1,后续变更则修改
	 */
	private String getLoanCapOverdueDate(List<BdRepayPlanTempVO> tempListAll) {
		// 逾期起时日
		String capOverdueDate = "";
		if (Objects.nonNull(tempListAll)) {
			for (int i = 0; i < tempListAll.size(); i++) {
				BdRepayPlanTempVO bdRepayPlanTempVO = tempListAll.get(i);
				if (BdLoanConstant.TERM_STATUS_2.equals(bdRepayPlanTempVO.getTermStatus())) {
					// 逾期起时日
					if (!StringUtil.isNullorBank(bdRepayPlanTempVO.getEndDate())) {
						capOverdueDate = DateUtility.format8To10(bdRepayPlanTempVO.getEndDate());
					}
					break;
				}
			}
		}
		return capOverdueDate;
	}
}
